package com.tsfyun.scm.controller.support;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.tsfyun.common.base.controller.BaseController;
import com.tsfyun.common.base.dto.FileQTO;
import com.tsfyun.common.base.dto.PaginationDto;
import com.tsfyun.common.base.dto.UploadFileDTO;
import com.tsfyun.common.base.enums.FileTypeEnum;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.util.FileUtil;
import com.tsfyun.common.base.vo.UploadFileVO;
import com.tsfyun.scm.service.file.IUploadFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @CreateDate: Created in 2020/12/1 17:45
 */
@RefreshScope
@Slf4j
@RestController
@RequestMapping(value = "/ueditorHandler")
public class UeditorHandlerController extends BaseController {

    @Value(value = "${file.realm.name:http://localhost:17777}")
    private String realmName;

    @Autowired
    private IUploadFileService uploadFileService;

    @RequestMapping(value = "/handle")
    public Map<String,Object> handle(HttpServletRequest request, @RequestParam(name = "action",required = false)String action, @RequestParam(name = "start",required = false,defaultValue = "1")Integer start){
        Map<String,Object> result = new LinkedHashMap<>();
        switch (action){
            case "config"://获取配置
                try{
                    ClassPathResource resource = new ClassPathResource("ueditor/config.json");
                    InputStream inputStream = resource.getInputStream();
                    String configJsonStr = IOUtils.toString(inputStream);
                    result = JSON.parseObject(configJsonStr,Map.class);
                }catch (Exception e){
                    log.error("读取ueditor配置数据异常",e);
                }
                break;
            case "uploadimage"://图片上传
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                MultipartFile file = multipartRequest.getFile("file");
                UploadFileDTO imgUpload = FileUtil.wrapUploadFileDto(file, FileTypeEnum.IMAGE.getCode(),"NEWIMG","notice","notice_image","公告图片");
                imgUpload.setUid("system");
                imgUpload.setUname("系统");
                try {
                    UploadFileVO uploadFileVO = uploadFileService.upload(imgUpload);
                    result.put("state","SUCCESS");
                    result.put("url",realmName + "/scm/download/file/" + uploadFileVO.getId());
                } catch (Exception e) {
                    log.error("图片上传失败",e);
                    if(e instanceof ServiceException) {
                        result.put("state",e.getMessage());
                    } else {
                        result.put("state","上传图片失败");
                    }
                }
                break;
            case "uploadfile"://文件上传
                multipartRequest = (MultipartHttpServletRequest) request;
                file = multipartRequest.getFile("file");
                UploadFileDTO fileUpload = FileUtil.wrapUploadFileDto(file, FileTypeEnum.FILE.getCode(),"NEWFILE","notice","notice_file","公告附件");
                fileUpload.setUid("system");
                fileUpload.setUname("系统");
                try {
                    UploadFileVO uploadFileVO = uploadFileService.upload(fileUpload);
                    result.put("state","SUCCESS");
                    result.put("url",realmName + "/scm/download/file/" + uploadFileVO.getId());
                } catch (Exception e) {
                    log.error("文件上传失败",e);
                    if(e instanceof ServiceException) {
                        result.put("state",e.getMessage());
                    } else {
                        result.put("state","上传文件失败");
                    }
                }
                break;
            case "listimage"://图片列表
                Integer imgLimit = 20;//每页显示20
                Integer imgPage = (start/imgLimit) + 1;
                PaginationDto imgPageInfo = new PaginationDto();
                imgPageInfo.setPage(imgPage);
                imgPageInfo.setLimit(imgLimit);
                FileQTO imgQTO = new FileQTO();
                imgQTO.setDocId("NEWIMG");
                imgQTO.setDocType("notice");
                imgQTO.setBusinessType("notice_image");
                try {
                    List<UploadFileVO> files = uploadFileService.list(imgPageInfo,imgQTO);
                    result.put("state","SUCCESS");
                    result.put("start",start);
                    result.put("total", CollUtil.isNotEmpty(files) ? files.size() : 0);
                    List<Map<String,String>> list = new ArrayList();
                    for(UploadFileVO uploadFileVO : files){
                        list.add(new LinkedHashMap<String, String>(){{
                            put("url",realmName + "/scm/download/file/" + uploadFileVO.getId());
                            put("mtime","");
                        }});
                    }
                    result.put("list",list);
                } catch (Exception e) {
                    log.error("获取图片列表失败",e);
                    if(e instanceof ServiceException) {
                        result.put("state",e.getMessage());
                    } else {
                        result.put("state","获取图片列表失败");
                    }
                }
                break;
            case "listfile"://文件集合
                Integer fileLimit = 20;//每页显示20
                Integer filePage = (start/fileLimit) + 1;
                PaginationDto filePageInfo = new PaginationDto();
                filePageInfo.setPage(filePage);
                FileQTO fileQTO = new FileQTO();
                fileQTO.setDocId("NEWFILE");
                fileQTO.setDocType("notice");
                fileQTO.setBusinessType("notice_file");
                try {
                    List<UploadFileVO> files = uploadFileService.list(filePageInfo,fileQTO);
                    result.put("state","SUCCESS");
                    result.put("start",start);
                    result.put("total", CollUtil.isNotEmpty(files) ? files.size() : 0);
                    List<Map<String,String>> list = new ArrayList();
                    for(UploadFileVO uploadFileVO : files){
                        list.add(new LinkedHashMap<String, String>(){{
                            put("url",realmName + "/scm/download/file/" + uploadFileVO.getId());
                            put("mtime","");
                        }});
                    }
                    result.put("list",list);
                } catch (Exception e) {
                    log.error("获取文件列表失败",e);
                    if(e instanceof ServiceException) {
                        result.put("state",e.getMessage());
                    } else {
                        result.put("state","获取附件列表失败");
                    }
                }
                break;
        }
        return result;
    }

}
